﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<el-tabs v-model="activeTab">
			<el-tab-pane label="基础信息" name="main">
				<el-card shadow="hover" class="layout-padding-auto create-form">
					<el-form ref="formRef" :model="stateData.vmModel" label-width="120px">
						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>单据信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_BillCode_FormItem" prop="Entity.BillCode">
										<template #label>
											<WtmLabelTooltip label="单据编号" tooltip="单据编号" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.BillCode" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_BillStatus_FormItem" prop="Entity.BillStatus">
										<template #label>
											<WtmLabelTooltip label="单据状态" tooltip="单据状态" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.BillStatus" disabled clearable class="width100">
											<el-option v-for="item in BILL_STATUS_OPTIONS" :key="item.value" :value="item.value" :label="item.label"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_WorkflowStatus_FormItem" prop="Entity.WorkflowStatus">
										<template #label>
											<WtmLabelTooltip label="工作流状态" tooltip="工作流状态" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.WorkflowStatus" disabled clearable class="width100">
											<el-option v-for="item in WORKFLOW_STATUS_OPTIONS" :key="item.value" :value="item.value" :label="item.label"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Remark_FormItem" prop="Entity.Remark">
										<template #label>
											<WtmLabelTooltip label="备注" tooltip="备注" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Remark" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>流程信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Approver_FormItem" prop="Entity.Approver">
										<template #label>
											<WtmLabelTooltip label="审批人" tooltip="流程审批人" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Approver" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_ApprovalTime_FormItem" prop="Entity.ApprovalTime">
										<template #label>
											<WtmLabelTooltip label="审批时间" tooltip="流程审批时间" />
										</template>
										<el-date-picker v-model="stateData.vmModel.Entity.ApprovalTime" disabled clearable class="width100"></el-date-picker>
									</el-form-item>
								</el-col>

								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_ApprovalOpinion_FormItem" prop="Entity.ApprovalOpinion">
										<template #label>
											<WtmLabelTooltip label="审批意见" tooltip="流程审批意见" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.ApprovalOpinion" clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>调动信息</span>
							</div>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_PersonId_FormItem" prop="Entity.PersonId">
										<template #label>
											<WtmLabelTooltip label="员工" tooltip="调动员工" />
										</template>
										<WtmPersonSelector
											v-model="stateData.vmModel.Entity.PersonId"
											:prefill-person="{
												ID: stateData.vmModel.Entity.PersonId,
												Name: stateData.vmModel.Entity.Name,
												StaffNo: stateData.vmModel.Entity.StaffNo,
											}"
											:disabled="true"
											:clearable="false"
										/>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_StaffNo_FormItem" prop="Entity.StaffNo">
										<template #label>
											<WtmLabelTooltip label="员工工号" tooltip="员工工号" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.StaffNo" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_Name_FormItem" prop="Entity.Name">
										<template #label>
											<WtmLabelTooltip label="员工姓名" tooltip="员工姓名" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.Name" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_ApplyDate_FormItem" prop="Entity.ApplyDate">
										<template #label>
											<WtmLabelTooltip label="申请日期" tooltip="申请日期" />
										</template>
										<el-date-picker v-model="stateData.vmModel.Entity.ApplyDate" disabled clearable class="width100"></el-date-picker>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_EffectiveDate_FormItem" prop="Entity.EffectiveDate">
										<template #label>
											<WtmLabelTooltip label="生效日期" tooltip="变更生效日期" />
										</template>
										<el-date-picker v-model="stateData.vmModel.Entity.EffectiveDate" disabled clearable class="width100"></el-date-picker>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_TransferType_FormItem" prop="Entity.TransferType">
										<template #label>
											<WtmLabelTooltip label="调整类型" tooltip="调整类型" />
										</template>
										<el-select v-model="stateData.vmModel.Entity.TransferType" disabled clearable class="width100">
											<el-option v-for="item in TRANSFER_TYPE_OPTIONS" :key="item.value" :value="item.value" :label="item.label"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="Entity_TransferReason_FormItem" prop="Entity.TransferReason">
										<template #label>
											<WtmLabelTooltip label="调整原因" tooltip="调整原因" />
										</template>
										<el-input type="textarea" v-model="stateData.vmModel.Entity.TransferReason" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<el-form-item ref="SupportingDocumentId_FormItem" prop="Entity.SupportingDocumentId">
										<template #label>
											<WtmLabelTooltip label="证明文件" tooltip="人事上传证明文件信息" />
										</template>
										<wtm-upload-file v-model="stateData.vmModel.Entity.SupportingDocumentId" clearable :multi="false" disabled></wtm-upload-file>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section" v-if="showPositionFields || showSalaryFields">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>原职位信息</span>
								<el-tag v-if="stateData.vmModel.Entity.TransferType === TRANSFER_TYPE.SALARY" size="small" type="info" style="margin-left: 10px">
									仅薪资信息
								</el-tag>
								<el-tag
									v-else-if="stateData.vmModel.Entity.TransferType === TRANSFER_TYPE.POSITION"
									size="small"
									type="warning"
									style="margin-left: 10px"
								>
									仅岗位信息
								</el-tag>
								<el-tag v-else-if="stateData.vmModel.Entity.TransferType !== null" size="small" type="success" style="margin-left: 10px">
									岗位和薪资信息
								</el-tag>
							</div>

							<WtmDeptSelector
								v-if="showPositionFields"
								v-model="stateData.vmModel.Entity.OriginalGroupId"
								prop="Entity.OriginalGroupId"
								label="原部门"
								:auth="false"
								:rules="[]"
								:positionRules="[]"
								:show-position="true"
								position-label="原岗位"
								v-model:position-id="stateData.vmModel.Entity.OriginalPositionId"
								:use-row="true"
								:dept-col="12"
								:position-col="12"
								:disabled="true"
								:position-disabled="true"
							/>

							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20" v-if="showRankFields">
									<el-form-item ref="Entity_OriginalRank_FormItem" prop="Entity.OriginalRank">
										<template #label>
											<WtmLabelTooltip label="原职级" tooltip="原职级" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.OriginalRank" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20" v-if="showSalaryFields">
									<el-form-item ref="Entity_OriginalBaseSalary_FormItem" prop="Entity.OriginalBaseSalary">
										<template #label>
											<WtmLabelTooltip label="原基本薪资" tooltip="原基本薪资" />
										</template>
										<el-input-number v-model="stateData.vmModel.Entity.OriginalBaseSalary" disabled clearable class="width100"></el-input-number>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20" v-if="showSalaryFields">
									<el-form-item ref="Entity_OriginalPositionSalary_FormItem" prop="Entity.OriginalPositionSalary">
										<template #label>
											<WtmLabelTooltip label="原岗位薪资" tooltip="原岗位薪资" />
										</template>
										<el-input-number v-model="stateData.vmModel.Entity.OriginalPositionSalary" disabled clearable class="width100"></el-input-number>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20" v-if="showSalaryFields">
									<el-form-item ref="Entity_OriginalPerformanceSalary_FormItem" prop="Entity.OriginalPerformanceSalary">
										<template #label>
											<WtmLabelTooltip label="原绩效薪资" tooltip="原绩效薪资" />
										</template>
										<el-input-number
											v-model="stateData.vmModel.Entity.OriginalPerformanceSalary"
											disabled
											clearable
											class="width100"
										></el-input-number>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section" v-if="showPositionFields || showSalaryFields">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>调整后信息</span>
								<el-tag v-if="stateData.vmModel.Entity.TransferType === TRANSFER_TYPE.SALARY" size="small" type="info" style="margin-left: 10px">
									仅薪资信息
								</el-tag>
								<el-tag
									v-else-if="stateData.vmModel.Entity.TransferType === TRANSFER_TYPE.POSITION"
									size="small"
									type="warning"
									style="margin-left: 10px"
								>
									仅岗位信息
								</el-tag>
								<el-tag v-else-if="stateData.vmModel.Entity.TransferType !== null" size="small" type="success" style="margin-left: 10px">
									岗位和薪资信息
								</el-tag>
							</div>

							<WtmDeptSelector
								v-if="showPositionFields"
								v-model="stateData.vmModel.Entity.NewGroupId"
								prop="Entity.NewGroupId"
								label="新部门"
								:auth="false"
								:rules="[]"
								:positionRules="[]"
								:show-position="true"
								position-label="新岗位"
								v-model:position-id="stateData.vmModel.Entity.NewPositionId"
								:use-row="true"
								:dept-col="12"
								:position-col="12"
								:disabled="true"
								:position-disabled="true"
							/>
							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20" v-if="showRankFields">
									<el-form-item ref="Entity_NewRank_FormItem" prop="Entity.NewRank">
										<template #label>
											<WtmLabelTooltip label="新职级" tooltip="新职级" />
										</template>
										<el-input v-model="stateData.vmModel.Entity.NewRank" disabled clearable class="width100"></el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20" v-if="showSalaryFields">
									<el-form-item ref="Entity_NewBaseSalary_FormItem" prop="Entity.NewBaseSalary">
										<template #label>
											<WtmLabelTooltip label="新基本薪资" tooltip="新基本薪资" />
										</template>
										<el-input-number v-model="stateData.vmModel.Entity.NewBaseSalary" disabled clearable class="width100"></el-input-number>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20" v-if="showSalaryFields">
									<el-form-item ref="Entity_NewPositionSalary_FormItem" prop="Entity.NewPositionSalary">
										<template #label>
											<WtmLabelTooltip label="新岗位薪资" tooltip="新岗位薪资" />
										</template>
										<el-input-number v-model="stateData.vmModel.Entity.NewPositionSalary" disabled clearable class="width100"></el-input-number>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20" v-if="showSalaryFields">
									<el-form-item ref="Entity_NewPerformanceSalary_FormItem" prop="Entity.NewPerformanceSalary">
										<template #label>
											<WtmLabelTooltip label="新绩效薪资" tooltip="新绩效薪资" />
										</template>
										<el-input-number v-model="stateData.vmModel.Entity.NewPerformanceSalary" disabled clearable class="width100"></el-input-number>
									</el-form-item>
								</el-col>
							</el-row>
						</div>

						<div class="form-section">
							<div class="section-title">
								<i class="_wtmicon _wtmicon-wxbzhanghu"></i>
								<span>工作信息</span>
							</div>
							<el-row :gutter="20">
								<el-col :xs="24" :lg="12" class="mb20">
									<WtmOrgSelector v-model="stateData.vmModel.Entity.OrgId" label="公司" prop="Entity.OrgId" :disabled="true" :auth="false" />
								</el-col>
								<el-col :xs="24" :lg="12" class="mb20">
									<WtmDeptSelector
										v-model="stateData.vmModel.Entity.GroupId"
										prop="Entity.GroupId"
										label="所属部门"
										:auth="false"
										:rules="[]"
										:disabled="true"
									/>
								</el-col>
							</el-row>
						</div>
					</el-form>
				</el-card>
			</el-tab-pane>

			<el-tab-pane label="审批信息" key="审批信息">
				<WtmWorkflowTimeline :entityId="stateData.vmModel.Entity.ID" entityType="HengTong.Model.Db.Bill.SysHrTransferRequestBill" />
			</el-tab-pane>
		</el-tabs>
	</div>
</template>

<script setup lang="ts" name="message._system.common.vm.edit;false">
import { reactive, ref, getCurrentInstance, onMounted, nextTick, computed, type ComponentInternalInstance } from 'vue';
import { ElMessage } from 'element-plus';
import { SysHrTransferRequestBillApi as api } from '/@/views/hr/syshrtransferrequestbill/api';
import other from '/@/utils/other';
import { ISysHrTransferRequestBillVm } from '/@/views/hr/syshrtransferrequestbill/api/interface';
import { IViewModel } from '/@/types/common';
import WtmWorkflowTimeline from '/@/components/workflowTimeline/index.vue';
import { useRouter } from 'vue-router';
import ApproveReasonDialog from '/@/components/approveReason/index.vue';

// 常量定义
const BILL_STATUS_OPTIONS = [
	{ value: '草稿', label: '草稿' },
	{ value: '正文', label: '正文' },
] as const;

const WORKFLOW_STATUS_OPTIONS = [
	{ value: '待提交', label: '待提交' },
	{ value: '提交中', label: '提交中' },
	{ value: '审核中', label: '审核中' },
	{ value: '已审批', label: '已审批' },
	{ value: '已驳回', label: '已驳回' },
] as const;

const WORKFLOW_STATUS = {
	PENDING: '待提交',
	SUBMITTING: '提交中',
	IN_AUDIT: '审核中',
	APPROVED: '已审批',
	REJECTED: '已驳回',
} as const;

const TRANSFER_TYPE_OPTIONS = [
	{ value: '岗位调整', label: '岗位调整' },
	{ value: '薪资调整', label: '薪资调整' },
	{ value: '岗位和薪资调整', label: '岗位和薪资调整' },
	{ value: '晋升', label: '晋升' },
	{ value: '降级', label: '降级' },
] as const;

// 调整类型常量
const TRANSFER_TYPE = {
	POSITION: '岗位调整',
	SALARY: '薪资调整',
	BOTH: '岗位和薪资调整',
	PROMOTION: '晋升',
	DEMOTION: '降级',
} as const;

const ACTIONS = {
	AGREE: '同意',
	REJECT: '拒绝',
} as const;

const BUTTON_TEXTS = {
	SUBMIT: '同意',
	REJECT: '拒绝',
	CLOSE: '关闭',
} as const;

const API_ENDPOINTS = {
	PERSONS: '/api/SysHrTransferRequestBill/GetSysPersons',
} as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);
const formRef = ref();
const activeTab = ref('main');

const stateData = reactive<IViewModel<ISysHrTransferRequestBillVm>>({
	vmModel: {
		Entity: {
			PersonId: null,
			StaffNo: null,
			Name: null,
			ApplyDate: null,
			EffectiveDate: null,
			TransferType: null,
			OrgId: null,
			OriginalGroupId: null,
			OriginalPositionId: null,
			OriginalRank: null,
			OriginalBaseSalary: null,
			OriginalPositionSalary: null,
			OriginalPerformanceSalary: null,
			NewGroupId: null,
			NewPositionId: null,
			NewRank: null,
			NewBaseSalary: null,
			NewPositionSalary: null,
			NewPerformanceSalary: null,
			TransferReason: null,
			Approver: null,
			ApprovalTime: null,
			ApprovalOpinion: null,
			GroupId: null,
			BillCode: null,
			BillStatus: null,
			WorkflowStatus: null,
			Remark: null,
			SupportingDocumentId: [],
		} as any,
		ActionName: null,
		IsMyApprove: null,
		Remark: null,
	},

	AllSysPersons: [] as any[],
});

// 计算属性
const isInAudit = computed(() => stateData.vmModel.Entity?.WorkflowStatus === WORKFLOW_STATUS.IN_AUDIT);
const canApprove = computed(() => !!stateData.vmModel.IsMyApprove);

// 字段显示控制的计算属性
const showPositionFields = computed(() => {
	const transferType = stateData.vmModel.Entity?.TransferType;
	return (
		transferType === TRANSFER_TYPE.POSITION ||
		transferType === TRANSFER_TYPE.BOTH ||
		transferType === TRANSFER_TYPE.PROMOTION ||
		transferType === TRANSFER_TYPE.DEMOTION
	);
});

const showSalaryFields = computed(() => {
	const transferType = stateData.vmModel.Entity?.TransferType;
	return (
		transferType === TRANSFER_TYPE.SALARY ||
		transferType === TRANSFER_TYPE.BOTH ||
		transferType === TRANSFER_TYPE.PROMOTION ||
		transferType === TRANSFER_TYPE.DEMOTION
	);
});

const showRankFields = computed(() => {
	const transferType = stateData.vmModel.Entity?.TransferType;
	return (
		transferType === TRANSFER_TYPE.POSITION ||
		transferType === TRANSFER_TYPE.BOTH ||
		transferType === TRANSFER_TYPE.PROMOTION ||
		transferType === TRANSFER_TYPE.DEMOTION
	);
});

// 统一的成功处理函数
const handleSuccess = () => {
	ElMessage.success(ci.proxy?.$t('message._system.common.vm.submittip') || '操作成功');
	emit('refresh');
	loading.value = false;
	closeDialog();
};

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 公共的审批处理函数
const handleApproval = (actionName: string) => {
	stateData.vmModel.ActionName = actionName;
	loading.value = true;
	formRef.value?.validate((valid: boolean) => {
		if (valid) {
			api()
				.approve(stateData.vmModel, stateData.vmModel.Entity.ApprovalOpinion ?? '')
				.then(handleSuccess)
				.catch(handleError);
		} else {
			loading.value = false;
		}
	});
};

// 取消
const onClose = () => {
	closeDialog();
};

// 通过
const onApprove = () => {
	other.openDialog('填写同意原因', ApproveReasonDialog, null, null, '30%', (reason: string) => {
		stateData.vmModel.Remark = reason;
		handleApproval(ACTIONS.AGREE);
	});
};

// 驳回
const onReject = () => {
	other.openDialog('填写拒绝原因', ApproveReasonDialog, { isRequired: true }, null, '30%', (reason: string) => {
		stateData.vmModel.Remark = reason;
		handleApproval(ACTIONS.REJECT);
	});
};

// 初始化页面数据
const initializePageData = () => {
	const wtmdata = ci.attrs['wtmdata'] as any;
	const routeId = useRouter().currentRoute.value.query.id;

	if (wtmdata?.ID) {
		stateData.vmModel.Entity.ID = wtmdata.ID;
	} else if (routeId) {
		stateData.vmModel.Entity.ID = routeId as any;
	}
};

// 加载选择列表数据
const loadSelectListData = async () => {
	try {
		const [persons] = await Promise.allSettled([other.getSelectList(API_ENDPOINTS.PERSONS, [], false)]);

		// 处理选择列表结果，即使部分失败也继续
		if (persons.status === 'fulfilled') stateData.AllSysPersons = persons.value;
	} catch (error) {
		// 静默处理错误
	}
};

// 加载实体数据
const loadEntityData = async () => {
	if (!stateData.vmModel.Entity.ID) {
		return;
	}

	try {
		const response = await api().get(stateData.vmModel.Entity.ID);
		other.setValue(stateData.vmModel, response);

		// 确保数据设置完成后再触发组件更新
		await nextTick();
	} catch (error) {
		ElMessage.error('加载数据失败，请重试');
		throw error;
	}
};

// 页面加载时
onMounted(async () => {
	loading.value = true;

	try {
		// 首先初始化页面数据（获取ID）
		initializePageData();

		// 并行加载选择列表数据和实体数据
		await Promise.all([loadSelectListData(), loadEntityData()]);
	} catch (error) {
		other.setFormError(ci, error);
	} finally {
		loading.value = false;
		nextTick(() => {
			setupHeaderButtons();
		});
	}
});

// 定义子组件向父组件传值事件
const emit = defineEmits(['refresh', 'closeDialog', 'updateHeaderButtons']);

// 关闭弹窗
const closeDialog = () => {
	emit('closeDialog');
};

// 设置对话框头部按钮
const setupHeaderButtons = () => {
	const headerButtons = [
		{
			text: BUTTON_TEXTS.SUBMIT,
			type: 'primary',
			onClick: onApprove,
			visible: isInAudit.value && canApprove.value,
		},
		{
			text: BUTTON_TEXTS.REJECT,
			type: 'danger',
			onClick: onReject,
			visible: isInAudit.value && canApprove.value,
		},
		{
			text: BUTTON_TEXTS.CLOSE,
			type: 'default',
			onClick: onClose,
			visible: true,
		},
	];

	emit('updateHeaderButtons', headerButtons);
};
</script>
